package com.chinaunicom.order.domain.service;

import com.chinaunicom.common.constants.Constants;
import com.chinaunicom.common.exception.BusinessException;
import com.chinaunicom.common.exception.ResponseCode;
import com.chinaunicom.order.domain.model.entity.CancelOrderEntity;
import com.chinaunicom.order.domain.model.entity.OrderEntity;
import com.chinaunicom.order.domain.model.valobj.OrderStatus;
import com.chinaunicom.order.domain.repository.IOrderRepository;
import com.chinaunicom.order.infrastructure.mq.DefaultProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author guomenghuai
 * @date 2024/1/15
 * @Description
 */
@Slf4j
@Service
public class OrderAfterService {

    @Resource
    private IOrderRepository orderRepository;

    @Autowired
    private DefaultProducer producer;

    public boolean cancelOrder(CancelOrderEntity cancelOrderEntity) {
        cancelOrderEntity.checkCancelOrderRequestParam();

        // 加入分布式锁控制
        try {

            // 执行取消订单
            return executeCancelOrder(cancelOrderEntity, cancelOrderEntity.getOrderId());

        } catch (Exception e) {
            log.error("关闭订单异常", e);
            throw  new BusinessException(e.getMessage());
        } finally {
            // 释放分布式锁
        }
    }

    private boolean executeCancelOrder(CancelOrderEntity cancelOrderEntity, Long orderId) {
        // 查询订单
        TransactionMQProducer transactionMQProducer = producer.getProducer();
        transactionMQProducer.setTransactionListener(new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                try {
                    // TODO 执行订单取消、更新订单状态

                    return LocalTransactionState.COMMIT_MESSAGE;
                } catch (Exception e) {
                    log.error("executeLocalTransaction error", e);
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                // 查询订单状态是否更新为“已取消”
                OrderEntity orderEntity = orderRepository.getByOrderId(orderId);
                if (OrderStatus.CANCELED.getCode().equals(orderEntity.getOrderStatus().getCode())) {
                    return LocalTransactionState.COMMIT_MESSAGE;
                }
                return LocalTransactionState.ROLLBACK_MESSAGE;
            }
        });

        try {
            // TODO 发送事务消息，释放库存
            return true;
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.SEND_TRANSACTION_MQ_FAILED);
        }
    }
}
